package org.sraosha.framework.controller;

import org.sraosha.framework.dto.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
public class NoHandlerFoundController implements ErrorController {

    @RequestMapping("/error")
    public ResponseEntity<ApiResult> handleError(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == 500) {
            log.error("statusCode：" + HttpStatus.INTERNAL_SERVER_ERROR.toString());
            return ApiResult.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR);
        } else if (statusCode == 404) {
            log.error("statusCode：" + HttpStatus.NOT_FOUND.toString());
            return ApiResult.error(HttpStatus.NOT_FOUND.value(), HttpStatus.NOT_FOUND.toString(), HttpStatus.NOT_FOUND);
        } else if (statusCode == 403) {
            log.error("statusCode：" + HttpStatus.FORBIDDEN.toString());
            return ApiResult.error(HttpStatus.FORBIDDEN.value(), HttpStatus.FORBIDDEN.toString(), HttpStatus.FORBIDDEN);
        } else {
            log.error("statusCode：" + statusCode);
            return ApiResult.error(null, null, null);
        }
    }
}
